package cn.edu.wzu.openlearning.controller;

import cn.edu.wzu.openlearning.mapper.UserMapper;
import cn.edu.wzu.openlearning.pojo.User;
import cn.edu.wzu.openlearning.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

@Controller
public class HomeController {

    @Autowired
    private UserService userService;

    /**
     * 首页的页面访问，只设置单纯的跳转
     * @param needPage
     * @return 页面访问
     */
    @RequestMapping(value = {"{needPage}"})
    public String pageViewer(@PathVariable String needPage){
        return needPage;
    }

    /**
     * 用户注册或者登录，没注册就登录了
     * @param user
     * @param session
     * @param model
     * @return
     */
    @RequestMapping(value = {"login.do","register.do"})
    public String loginOrRegister(User user, HttpSession session,Model model){
        User sessionUser = (User) session.getAttribute("user");
        if (sessionUser != null)
            //如果 用户存在Session，则返回首页，不能重复登录
            return "redirect:index";
        else {
            // 用户不存在
            User realUser = userService.loginOrRegister(user);
            if(realUser != null){
                // 登录成功
                session.setAttribute("user",realUser);
                return "redirect:index";
            } else {
                //登录失败，返回为什么失败
                session.setAttribute("error","密码错误");
                return "login";
            }
        }
    }

    @RequestMapping(value = {"quit.do","exit.do"})
    public String userQuit(HttpSession session){
        User sessionUser = (User) session.getAttribute("user");
        if (sessionUser != null){
            session.removeAttribute("user");
            Enumeration em = session.getAttributeNames();
            while(em.hasMoreElements()){
                session.removeAttribute(em.nextElement().toString());
            }
        }
        return "redirect:index";

    }


}
